import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:secverify_plugin/secverify.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:sharesdk_plugin/sharesdk_register.dart';
import 'package:sph_shipper/Login/ChooseCountryList.dart';
import 'package:sph_shipper/Login/MobLogin.dart';
import 'dart:io';


import '../AppConfig/Config.dart';
import '../AppConfig/CustomButton.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../Main/CustomerService/ChangNewPhoneNumber.dart';
import '../Main/CustomerService/VerifyPhoneUserID.dart';
import '../Main/ProtocolDisplay.dart';
import '../http/api.dart';
import '../http/getapi.dart';
import '../l10n/messages.dart';
import 'SMSView.dart';


class LoginVC extends StatefulWidget {
  const LoginVC({super.key});

  @override
  State<LoginVC> createState() => _LoginVCState();
}

class _LoginVCState extends State<LoginVC> {
  DateTime? lastPressed;
  @override
  Widget build(BuildContext context) {
    return WillPopScope(

        onWillPop: () async {
      final now = DateTime.now();
      // 如果 lastPressed 为空或者间隔时间超过 2 秒，则更新 lastPressed 并提示用户
      if (lastPressed == null || now.difference(lastPressed!) > Duration(seconds: 2)) {
        lastPressed = now;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('再按一次退出'),
            duration: Duration(seconds: 2),
          ),
        );
        return false; // 不退出
      }
      return true; // 退出应用

    },
    child:
      Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white10,
          elevation: 0,

        ),
        body: ListView(
          children: [
            SizedBox(height: 36.h),
            Container(
              margin: EdgeInsets.only(left: 30.h),
              alignment: Alignment.centerLeft,
              height: 60.h,
              width: 181.w,

              child:Image.asset("lib/Images/login/欢迎使用速配货货主版.png"),
            ),
            SizedBox(height: 36.h),
            MobileSms(),


          ],
        )
      ),
    );
  }
}




class MobileSms extends StatefulWidget {
  const MobileSms({super.key});

  @override
  State<MobileSms> createState() => _MobileSmsState();
}

class _MobileSmsState extends State<MobileSms> {
  int count = 0;
  String phoneNum = "";
  String smsCode = "";
  String CountryNum = "+86";
  String isAgree = "0";
  String verificationResult = '';
  bool _isButtonEnabled = true;
  DateTime? lastPressed;
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return WillPopScope(
        onWillPop: () async {
      // 返回false禁用手势返回
      return Future.value(true);
    },
    child:
      Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          height: 40.h,
          width: 300.w,
          margin: EdgeInsets.only(left: 30.w,right: 30.w),
          alignment: Alignment.centerLeft,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(30),
            color: Color.fromRGBO(248, 248, 248, 1),
          ),
          child: Row(
            children: [
              TextButton(onPressed: ()async{
                final result=await    Navigator.push( context, FadeRoute(page:ChooseCountryList()));
                if(result!=null){
                  setState(() {
                    CountryNum=result;
                  });

                }
              }, child: Text(CountryNum,style: TextStyle(color: Colors.black,fontSize: 14.sp),)),
              Icon(Icons.arrow_drop_down,color: Colors.black,),
              Text("丨",style: TextStyle(color: Color.fromRGBO(183, 183, 183, 1),)),
              Container(
                height: 40.h,
                width: 180.w,
                alignment: Alignment.centerLeft,
                child:TextField(
                  style: TextStyle(color: Colors.black,fontSize: 14.sp),
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(

                    filled: true,
                    fillColor: Color.fromRGBO(248, 248, 248, 1),

                    hintText: messages["请输入手机号码"],

                    //边框
                    focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Color.fromRGBO(248, 248, 248, 1))),
                    enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color:Color.fromRGBO(248, 248, 248, 1),)),

                    hintStyle: TextStyle(
                      color: Color.fromRGBO(183, 183, 183, 1),
                      fontSize:  MyFontSizes.commonrText.sp,
                    ),
                  ),
                  onChanged: (value) {
                    setState(() {
                      phoneNum = value;
                    });
                  },

                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 20.h,),
        CustomButton(
              enabled:phoneNum.length==11?true:false,
              width: screenSize.width-60.w,
              height: 40.h,
              borderRadius: 30,
              text: '获取验证码',
              normalColor: phoneNum.length==11?MyColors.themeColor: MyColors.clickColor,
              pressedColor: Colors.white,
              customOnPressed: () {
                if (isAgree=="1") {
                  setState(() {
                    _isButtonEnabled =false;
                  });
                  getApiManager.getData(
                    context, // 上下文对象，用于显示提示信息等
                    'api/auth/auth/shipper/getPhoneValidCode', // 您的API端点
                    {"phone":phoneNum,"codeType":"LOGIN"}, // 查询参数，如果没有可以传递null
                        (responseData) async {
                      BrnToast.show(
                        "发送成功",
                        context,
                        duration: BrnDuration.short,
                      );
                      Navigator.push( context, FadeRoute(page:SMSView(
                        phoneNumber: phoneNum, validCodeReqNo: responseData['data']['validCodeReqNo'],)));
                    },
                  );

                }else{
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return BrnDialog(
                        titleText: "请阅读并同意用户协议",
                        actionsWidget: [
                          TextButton(
                            onPressed: () {
                              Navigator.pop(context);
                              FocusScope.of(context).unfocus();
                            },
                            child: Text("取消",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                          ),
                          TextButton(
                            onPressed: () {
                              setState(() {
                                isAgree="1";

                                setState(() {
                                  _isButtonEnabled =false;
                                });
                                getApiManager.getData(
                                  context, // 上下文对象，用于显示提示信息等
                                  'api/auth/auth/shipper/getPhoneValidCode', // 您的API端点
                                  {"phone":phoneNum,"codeType":"LOGIN"}, // 查询参数，如果没有可以传递null
                                      (responseData) async {
                                    BrnToast.show(
                                      "发送成功",
                                      context,
                                      duration: BrnDuration.short,
                                    );
                                    Navigator.pop(context);
                                    Navigator.push( context, FadeRoute(page:SMSView(
                                      phoneNumber: phoneNum, validCodeReqNo: responseData['data']['validCodeReqNo'],)));
                                  },
                                );
                              });
                            },
                            child: Text("同意",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                          ),

                        ],
                      );
                    },
                  );
                }
              },

            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                TextButton(onPressed: (){
                  Navigator.push( context, FadeRoute(page:VerifyPhoneUserID()));
                }, child: Text("手机号不用了无法登陆？",style: TextStyle(color: MyColors.authTipColor),)),
                SizedBox(width: 20.w,),
              ],
            ),

        SizedBox(height: 10.h,),
        Container(
          height: 40.h ,
          margin: EdgeInsets.only(left: 30.w,right: 30.w),
          child: MobLogin(),


        ),
        SizedBox(height:screenSize.height/7),
        Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                "lib/Images/login/line.png",
                height: 1.h,
                width:20.w,
              ),
              Text("其他方式登录",style: TextStyle(color: Colors.grey,fontSize: MyFontSizes.smallText.sp),),
              Image.asset(
                "lib/Images/login/line.png",
                height: 1.h,
                width:20.w,),
            ]
        ),




        SizedBox(height: 10.h,),
        ThirdView(),
        SizedBox(height: 30.h,),
        Container(
          margin: EdgeInsets.only(left: 10, right: 10),
          child: Row(
            children: [
              Column(
                children: [
                  IconButton(
                    onPressed: () => {
                      setState(() {
                        if (isAgree == "1") {
                          isAgree = "0";
                        } else {
                          isAgree = "1";
                        }
                      })
                    },
                    icon:isAgree == "0" ? Icon(Icons.radio_button_unchecked,size: 20,): Icon(Icons.radio_button_checked,size: 20,),
                    color: isAgree == "1" ? Colors.orange : Colors.grey,
                  ),
                  SizedBox(height: 25.h,),
                ],
              ),
              Container(
                width: 290.w,
                child:  RichText(
                  text: TextSpan(children: [

                    TextSpan(
                        text: '已阅读并同意 ',
                        style: TextStyle(fontSize: 12.sp, color: Colors.black54)),
                    TextSpan(
                        text: '《速配货用户协议》',
                        style: TextStyle(fontSize: MyFontSizes.commonrText.sp, color: MyColors.blueColor),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1760507434822107138",)));
                          }),
                    TextSpan(
                        text: '《速配货隐私政策》',
                        style: TextStyle(fontSize: 12.sp, color: MyColors.blueColor),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1805853139653627905",)));
                          }),

                    TextSpan(
                        text: '《第三方合作清单》',
                        style: TextStyle(fontSize:12.sp, color: MyColors.blueColor),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1806571891806515202",)));
                          }),
                    TextSpan(
                        text: ',未注册的手机号将自动完成账号注册',
                        style: TextStyle(fontSize: 12.sp, color: Colors.black54)),
                  ]),
                ),
              ),

            ],
          ),

        ),


      ],
      ),
    );




  }
}


class ThirdView extends StatefulWidget {
  const ThirdView({super.key});

  @override
  State<ThirdView> createState() => _ThirdViewState();
}

class _ThirdViewState extends State<ThirdView> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    ShareSDKRegister register = ShareSDKRegister();
    register.setupWechat(
        "wx829fa0e5125a100c ", "888addbe33fbb69decfbc34673f2f08d", "https://app.sph56.cn/");

    register.setupDouyin(
      "awuv8755a0sug9lk", "f31cb3a28dd4595b5953191aa4520c9c",);
    register.setupQQ("100371282", "aed9b0303e3ed1e27bae87c33761161d");

    SharesdkPlugin.regist(register);
  }
  /// @param 隐私协议返回数据的格式
  /// POLICY_TYPE_URL = 1
  /// POLICY_TYPE_TXT = 2
  getPrivacyPolicyUrl(BuildContext context) {
    SharesdkPlugin.getPrivacyPolicy("1", "en-CN", (dynamic data, dynamic error) {
      String? policyData, errorStr;
      if (data != null) {
        policyData = data["data"];
        print("==============>policyData " + policyData!);
      }

      if (error != null) {
        errorStr = error["error"];
        print("==============>errorStr " + errorStr!);
      }

      if (policyData != null) {
        print("隐私协议"+ policyData);
      } else if (errorStr != null) {
        print("隐私协议"+ errorStr);
      } else {
        print("隐私协议"+ "获取隐私协议失败:此接口已废弃");
      }
    });
  }
  submitPrivacyGrantResult(BuildContext context) {
    SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {
      if (success == true) {
        print("隐私协议授权提交结果:"+"成功");
      } else {
        print("隐私协议授权提交结果:"+ "失败");
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return  Container(
      margin: EdgeInsets.only(left: 10, right: 10),


      child:   Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(

            child: Image.asset(
              "lib/Images/login/微信登录.png",
              height: 50.h,
              width:40.w,
            ),
            onTap: ()async {
              SharesdkPlugin.getUserInfo(ShareSDKPlatforms.wechatSession,
                      (SSDKResponseState state, dynamic user, SSDKError error) {
                    print(user != null ? user : error.rawData);
                  });
            },
          ),
          SizedBox(
            width: 40.w,
          ),
          GestureDetector(
            child: Image.asset(
              "lib/Images/login/抖音登录.png",
              height: 40.h,
              width: 40.w,
            ),
            onTap: () async{
              SharesdkPlugin.getUserInfo(ShareSDKPlatforms.douyin,
                      (SSDKResponseState state, dynamic user, SSDKError error) {
                    print(user != null ? user : error.rawData);
                  });
            },
          ),

          SizedBox(
            width:Platform.isIOS? 40.w:0,
          ),
          Platform.isIOS?GestureDetector(
            child: Image.asset(
              "lib/Images/login/苹果登录.png",
              height: 40.h,
              width:40.w,
            ),
            onTap: () {
              SharesdkPlugin.getUserInfo(ShareSDKPlatforms.apple,
                      (SSDKResponseState state, dynamic user, SSDKError error) {
                    print(user != null ? user : error.rawData);
                  });

            },
          ):SizedBox(width: 0,),
        ],
      ),
    );







  }
}
